import React, { useState } from 'react';
import { Autocomplete, TextField, Box } from '@mui/material';
import { open } from '@tauri-apps/plugin-dialog';
import { homeDir, join } from '@tauri-apps/api/path';
import { Download, Image, Description, DesktopWindows, FolderOpen } from '@mui/icons-material';

export default function DirectorySelect({ value, onChange }) {
  const [directories, setDirectories] = useState(null);
  const [inputValue, setInputValue] = useState('');

  // 初始化常用目录
  const initDirectories = async () => {
    if (directories) return;
    
    const home = await homeDir();
    setDirectories({
      downloads: await join(home, 'Downloads'),
      pictures: await join(home, 'Pictures'),
      documents: await join(home, 'Documents'),
      desktop: await join(home, 'Desktop'),
    });
  };

  // 处理打开事件
  const handleOpen = () => {
    initDirectories();
  };

  // 处理选项变更
  const handleChange = async (event, newValue) => {
    if (newValue === 'custom') {
      // 打开目录选择对话框
      const selectedPath = await open({
        directory: true,
        multiple: false,
        defaultPath: await homeDir(),
      });
      
      if (selectedPath) {
        onChange(selectedPath);
        setInputValue(selectedPath);
      }
    } else if (newValue) {
      onChange(newValue);
      setInputValue(newValue);
    }
  };

  // 处理输入变更
  const handleInputChange = (event, newInputValue) => {
    setInputValue(newInputValue);
    onChange(newInputValue);
  };

  // 获取选项列表
  const getOptions = () => {
    if (!directories) return ['custom'];
    return [...Object.values(directories), 'custom'];
  };

  // 获取选项显示文本
  const getOptionLabel = (option) => {
    if (option === 'custom') return '选择下载目录...';
    return option;
  };

  // 获取选项在下拉列表中的显示文本
  const getOptionDisplay = (option) => {
    if (option === 'custom') return { icon: <FolderOpen />, label: '选择下载目录...' };
    if (directories) {
      const entry = Object.entries(directories).find(([_, path]) => path === option);
      if (entry) {
        const [key] = entry;
        const labels = {
          downloads: { icon: <Download />, label: '下载' },
          pictures: { icon: <Image />, label: '图片' },
          documents: { icon: <Description />, label: '文档' },
          desktop: { icon: <DesktopWindows />, label: '桌面' }
        };
        return labels[key];
      }
    }
    return { icon: <FolderOpen />, label: option };
  };

  return (
    <Autocomplete
      freeSolo
      value={value}
      inputValue={inputValue}
      options={getOptions()}
      getOptionLabel={getOptionLabel}
      onChange={handleChange}
      onInputChange={handleInputChange}
      onOpen={handleOpen}
      renderInput={(params) => (
        <TextField
          {...params}
          label="下载目录"
          placeholder="输入或选择下载目录"
          fullWidth
        />
      )}
      renderOption={(props, option) => {
        const { icon, label } = getOptionDisplay(option);
        return (
          <Box component="li" {...props} sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            {icon}
            {label}
          </Box>
        );
      }}
    />
  );
}